<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    table {
        caret-color: transparent;
    }
</style>
<body>
    <div>
        <button id="btn">点击</button>
        <input type="text" name="" id="datainput">
    </div>
    <div>
        <table id="tb">
            <tr></tr>
        </table>
    </div>
</body>
<script>
    let btn = document.getElementById("btn");
    let tb = document.getElementById("tb");
    btn.onclick = function(e) {
        let input = document.getElementById("datainput");
        let value = input.value;
        let addData = {msg: value};
        fetch("http://192.168.42.166:3000/api/adddata" , {
            method: "POST",
            body: JSON.stringify(addData)
        }).then(res => res.json())
        .then(res => {
            console.log(res);
            tb.innerHTML = '';
            creatList(res);
        })
        input.value = '';
        input.focus();
    }

    function creatList(res) {
        for(let i = 0 ; i < res.length; i++) {
            let trObj = document.createElement("tr");
            let tb = document.getElementById("tb");
            trObj.innerHTML = `
                <td>${res[i].msg}<td>
                <td><button id = ${res[i].id} class = "del">删除</button></td>
            `
            tb.appendChild(trObj);
        }
    }

    window.onload = function() {
        fetch("http://192.168.42.166:3000/api/list")
            .then(res => res.json())
            .then(res => {
                console.log(res);
                creatList(res);
            })
    }
    tb.onclick = (e) => {
        console.log(e.target.id);
        delData(e.target.id);
    }
    function delData(id) {
        fetch("http://192.168.42.166:3000/api/del" , {method: "POST" , body: id})
            .then(res => res.json())
            .then(res => {
                console.log(res);
                tb.innerHTML = "";
                creatList(res);
            })
    }
</script>
</html>